/*
 * myimagepanel.cpp
 *
 *  Created on: Mar 1, 2013
 *      Author: RDU
 */
#include "myimagepanel.h"
#include "../ImageStitching/autostitch.h"

BEGIN_EVENT_TABLE(MyImagePanel,wxPanel)
	EVT_PAINT(MyImagePanel::OnPaint)
	EVT_SIZE(MyImagePanel::OnSize)
END_EVENT_TABLE()

MyImagePanel::MyImagePanel(wxWindow* parent, const wxPoint& pos, const wxSize& size):
	wxPanel(parent,-1,pos,size,wxTAB_TRAVERSAL)
{
	m_bDrawing=false;
	m_nWidth=size.GetWidth();
	m_nHeight=size.GetHeight();
	m_imageDefault.LoadFile(wxT("default.jpg"), wxBITMAP_TYPE_JPEG);
	m_imageLoad.LoadFile(wxT("default.jpg"), wxBITMAP_TYPE_JPEG);
}

MyImagePanel::~MyImagePanel()
{

}

void MyImagePanel::Draw(wxDC& dc)
{
	int newWidth, newHeight;

	if(!dc.Ok())	return;

	dc.GetSize( &newWidth, &newHeight );

	if(m_imageLoad.Ok())
	{
		m_bDrawing=true;

		//m_imageLoad=m_imageLoad.Scale(m_nWidth,m_nHeight);

		if( newWidth != m_nWidth || newHeight != m_nHeight )
		{
			m_bitMap = wxBitmap( m_imageLoad.Scale( newWidth, newHeight /*, wxIMAGE_QUALITY_HIGH*/ ) );
			m_nWidth = newWidth;
			m_nHeight = newHeight;
			dc.DrawBitmap( m_bitMap, 0, 0, false );
		}
		else
		{
			m_bitMap=wxBitmap(m_imageLoad.Scale(m_nWidth,m_nHeight));
			dc.DrawBitmap( m_bitMap, 0, 0, false );
		}

		m_bDrawing=false;
	}
	else if(m_imageDefault.Ok())
	{
		m_bDrawing=true;

		if( newWidth != m_nWidth || newHeight != m_nHeight )
		{
			m_bitMap = wxBitmap( m_imageDefault.Scale( newWidth, newHeight /*, wxIMAGE_QUALITY_HIGH*/ ) );
			m_nWidth = newWidth;
			m_nHeight = newHeight;
			dc.DrawBitmap( m_bitMap, 0, 0, false );
		}
		else
		{
			m_bitMap=wxBitmap(m_imageDefault.Scale(m_nWidth,m_nHeight));
			dc.DrawBitmap( m_bitMap, 0, 0, false );
		}

		m_bDrawing=false;
	}
	else
	{
		wxMessageBox(wxT("Sorry, no image could be displayed!"));
		return;
	}
}

wxImage MyImagePanel::CvMat2WxImage(const Mat& cvImg)
{
	// data dimension
	wxImage wxImg;
	int w = cvImg.cols;
	int h = cvImg.rows;
	int size = w*h*3*sizeof(byte);

	// allocate memory for internal wxImage data
	byte* wxData = (byte*) malloc(size);

	// the matrix stores BGR image for conversion
	Mat cvRGBImg = Mat(h, w, CV_8UC3, wxData);

	int mapping[] = {0,2,1,1,2,0}; // CV(BGR) to WX(RGB)
	mixChannels(&cvImg, 1, &cvRGBImg, 1, mapping, 3);

	wxImg.Destroy(); // free existing data if there's any
	wxImg = wxImage(w, h, wxData);

	return wxImg;
}

void MyImagePanel::DrawPano(Mat cvImage)
{
	if(m_bDrawing)	return;

	m_bDrawing=true;

	if(cvImage.empty())
		m_imageLoad=m_imageDefault;
	else
		m_imageLoad = CvMat2WxImage(cvImage);

	m_bDrawing=false;

	Refresh(FALSE);
	Update();
}

void MyImagePanel::OnPaint(wxPaintEvent& event)
{
	wxPaintDC dc(this);

	Draw(dc);
}

void MyImagePanel::OnSize(wxSizeEvent& event)
{
	Refresh();
	event.Skip();
}
